/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.upf.grupof.projectphotos.databases;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.Database;
import org.xmldb.api.base.XMLDBException;


/**
 *
 * @author fredi
 */
public class XmlDbDataSource implements iXmlDbDataSource {

    private final static Log log = LogFactory.getLog(XmlDbDataSource.class);
    private static XmlDbDataSource instance = new XmlDbDataSource();
    private String URI;
    private final String driverName = "XmlDbDataSource/driverClassName";
    private final String URL = "XmlDbDataSource/url";
    private final String properties = "conf.properties";

    public static XmlDbDataSource getInstance() {
        return instance;
    }

    private XmlDbDataSource(){
        try {
            Properties dbprop = loadProperties();
            String driver = dbprop.getProperty(driverName);
            URI = dbprop.getProperty(URL);
            Class cl = Class.forName(driver);
            Database database = (Database) cl.newInstance();
            DatabaseManager.registerDatabase(database);

        } catch (XMLDBException ex) {
            log.error("Error en DatabaseManager.registerDatabase(database)");
        } catch (InstantiationException ex) {
            log.error("Error en Database database = (Database)cl.newInstance()");
        } catch (IllegalAccessException ex) {
            log.error("Error en Database database = (Database)cl.newInstance()");
        } catch (ClassNotFoundException ex) {
            log.error("Error en Class cl = Class.forName(driver)");
        } catch (IOException ex) {
            log.error("Error en Properties dbprop = loadConfig()");
        }
    }

    private Properties loadProperties() throws IOException {
        Properties dbprop = new Properties();
        InputStream is = iXmlDbDataSource.class.getClassLoader().getResourceAsStream(properties);
        InputStreamReader isr = null;
        try {
            isr = new InputStreamReader(is, "UTF-8");
            dbprop.load(isr);
        } finally {
            if (isr != null) {
                isr.close();
            }
            if (is != null) {
                is.close();
            }
        }

        return dbprop;
    }

    public Collection getCollection() throws XMLDBException {
        return DatabaseManager.getCollection(URI);
    }

    public Collection getCollection(String aUserName, String aPassword) throws XMLDBException {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}